package com.stars.easyms.datasource.boot;

import com.stars.easyms.datasource.common.EasyMsDataSourceConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.EnumerablePropertySource;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * <p>className: EasyMsDatasourceApplicationContextInitializer</p>
 * <p>description: EasyMs数据源ApplicationContext初始化类</p>
 *
 * @author guoguifang
 * @version 1.7.0
 * @date 2020/10/26 7:30 下午
 */
@Slf4j
public class EasyMsDatasourceApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered {

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        CompositePropertySource compositePropertySource = new CompositePropertySource(EasyMsDataSourceConstant.PROPERTY_SOURCE_NAME);
        compositePropertySource.addPropertySource(new ConfigPropertySource(getEasyMsDatasourceInitProperties()));
        applicationContext.getEnvironment().getPropertySources().addFirst(compositePropertySource);
    }

    private static class ConfigPropertySource extends EnumerablePropertySource<Map<String, String>> {

        private static final String[] EMPTY_ARRAY = new String[0];

        ConfigPropertySource(Map<String, String> source) {
            super(EasyMsDataSourceConstant.MODULE_NAME, source);
        }

        @Override
        public String[] getPropertyNames() {
            Set<String> propertyNames = this.source.keySet();
            if (propertyNames.isEmpty()) {
                return EMPTY_ARRAY;
            }
            return propertyNames.toArray(new String[0]);
        }

        @Override
        public Object getProperty(String name) {
            return this.source.get(name);
        }

    }

    private Map<String, String> getEasyMsDatasourceInitProperties() {
        Map<String, String> map = new HashMap<>(8);
        map.put("spring.datasource.type", "com.stars.easyms.datasource.EasyMsMultiDataSource");
        return map;
    }

    /**
     * springboot模式下ApplicationContextInitializer的顺序
     */
    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE + 1;
    }
}